package cn.tworice.mybatis.handler;


import cn.tworice.auth.util.LoginUserUtil;
import cn.tworice.common.util.StringUtils;
import cn.tworice.mybatis.po.BasicDO;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import java.util.Objects;

/**
 * 通用参数填充
 * @author 二饭
 */
public class DefaultDBFieldHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        if (Objects.nonNull(metaObject) && metaObject.getOriginalObject() instanceof BasicDO) {
            BasicDO baseDO = (BasicDO) metaObject.getOriginalObject();
            long current = System.currentTimeMillis();
            // 创建时间为空，则以当前时间为插入时间
            if (Objects.isNull(baseDO.getCreateTime())) {
                baseDO.setCreateTime(current);
            }
            // 更新时间为空，则以当前时间为更新时间
            if (Objects.isNull(baseDO.getUpdateTime())) {
                baseDO.setUpdateTime(current);
            }

            String userId = LoginUserUtil.getLoginUserId();
            // 当前登录用户不为空，创建人为空，则当前登录用户为创建人
            if (Objects.nonNull(userId) && StringUtils.isBlank(baseDO.getCreator())) {
                baseDO.setCreator(userId);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (Objects.nonNull(metaObject) && metaObject.getOriginalObject() instanceof BasicDO){
            BasicDO baseDO = (BasicDO) metaObject.getOriginalObject();
            baseDO.setUpdateTime(System.currentTimeMillis());
        }
    }
}
